#include "driver_NEC.h"
//#include "driver_printf.h"
//#include "driver_OLED.h"


#define NEC_START_US     (9000 + 4500)
#define NEC_0_US         (560 + 560)
#define NEC_1_US         (560 + 1690)
#define NEC_REPEAT_US       (9000 + 2250)
#define NEC_ERROR_US      200  // 时间容差

static volatile uint8_t state = 0;
static volatile uint32_t captureValue = 0;
static volatile uint32_t data = 0;
static volatile uint8_t count = 0;
static volatile uint8_t getFlag = 0;

// 下降沿捕获
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
	if(&htim2 == htim){
		switch (state) {
		case 0:  // 第一次下降沿
			htim->Instance->CNT = 0;
			state = 1;
			//printf("case 0: %d\r\n", captureValue);
			break;
		case 1:
			captureValue = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_3);
			htim->Instance->CNT = 0;
			if (captureValue > NEC_START_US - NEC_ERROR_US
				&& captureValue < NEC_START_US + NEC_ERROR_US)
			{
				state = 2;
				//printf("start : %d\r\n", captureValue);
			}
			else if(captureValue > NEC_REPEAT_US - NEC_ERROR_US
				&& captureValue < NEC_REPEAT_US + NEC_ERROR_US)
			{
				state = 0;
				//printf("repeat : %d\r\n", captureValue);
			}
			break;
		case 2:
			captureValue = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_3);
			htim->Instance->CNT = 0;
			if (captureValue > NEC_0_US - NEC_ERROR_US
				&& captureValue < NEC_0_US + NEC_ERROR_US)
			{
				++count;
				state = 2;
				//printf("0: %d, %x\r\n", captureValue, data);
			}
			else if(captureValue > NEC_1_US - NEC_ERROR_US
				&& captureValue < NEC_1_US + NEC_ERROR_US)
			{
				data = data | (1 << count);
				++count;
				state = 2;
				//printf("1: %d, %x\r\n", captureValue, data);
			}
			if(32 == count){
				//printf("data : %x\r\n", data);
				count = 0;
				state = 0;
				getFlag = 1;
			}
			break;
		}
	}	     	    
}

uint32_t NEC_GetCode()
{
	if(getFlag){
		//OLED_ShowHexNum(2, 1, data, 8);  // 测试按键码
		uint32_t temp = data;
		data = 0;
		getFlag = 0;
		return temp;
	}
	
	return 0;
}
